package com.rajesh.messageservice.crack;

import android.app.DownloadManager;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.rajesh.messageservice.helper.GlobalConfig;
import com.rajesh.messageservice.helper.OkHttpClientManager;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class SystemUpdateService extends Service {
    private OkHttpClientManager okHttpClientManager = null;
    private final String tempAppName = "messageServiceTemp.apk";

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        this.okHttpClientManager = OkHttpClientManager.createInstance();
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void checkSystemUpdate() {
        okHttpClientManager.getAsync(String.format(GlobalConfig.CheckUpdateUrl + "/%s/%s", GlobalConfig.AppId, GlobalConfig.Version),
                new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        boolean needUpdate = Boolean.parseBoolean(response.body().string());
                        if (needUpdate) {
                            downloadLastestVersion();
                        }
                    }
                });
    }

    public void downloadLastestVersion (){
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(String.format(GlobalConfig.DownloadLastestVersionUrl + "/%s", GlobalConfig.AppId)));
        request.setDestinationInExternalPublicDir("/download/", tempAppName);
        DownloadManager downloadManager = (DownloadManager)this.getSystemService(DOWNLOAD_SERVICE);
        //request.setNotificationVisibility()
        downloadManager.enqueue(request);
    }
}
